package cn.iocoder.yudao.boot.common.validate;

import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.boot.common.util.validation.ValidationUtils;

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.*;

@Target({
        ElementType.METHOD,
        ElementType.FIELD,
        ElementType.ANNOTATION_TYPE,
        ElementType.CONSTRUCTOR,
        ElementType.PARAMETER,
        ElementType.TYPE_USE
})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(
        validatedBy = MobileAnno.MobileValidator.class
)
public @interface MobileAnno {

    String message() default "手机号格式不正确";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};


    class MobileValidator implements ConstraintValidator<MobileAnno, String> {

        @Override
        public void initialize(MobileAnno annotation) {
        }

        @Override
        public boolean isValid(String value, ConstraintValidatorContext context) {
            // 如果手机号为空，默认不校验，即校验通过
            if (StrUtil.isEmpty(value)) {
                return true;
            }
            // 校验手机
            return ValidationUtils.isMobile(value);
        }

    }

}
